package cn.xing.managementSystem.controller;

import cn.xing.managementSystem.domain.ImageStore;
import cn.xing.managementSystem.service.ImageStoreService;
import cn.xing.managementSystem.utils.Preconditions;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author cuixing
 * @package cn.xing.managementSystem.controller
 * @class EditorDemoController
 * @email xing.cui@magicwindow.cn
 * @date 2018/4/22 下午10:13
 * @description
 */

@Controller
public class ImageStoreController {

    @Autowired
    private ImageStoreService imageStoreService;

    @Value("${image.url}")
    private String imageUrl;

    @RequestMapping("/upload")
    @ResponseBody
    public JSONObject upload(HttpServletRequest request) throws IOException {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        JSONObject result = new JSONObject();
        result.put("errno", 0);
        JSONArray pathArr = new JSONArray();
        result.put("data", pathArr);
        if(Preconditions.isNotBlank(files)){
            for(MultipartFile file : files){
                ImageStore imageStore = imageStoreService.saveImageStore(file);
                pathArr.add(String.format(imageUrl, imageStore.getId()));
            }
        }
        return result;
    }


    @RequestMapping(value = "showImage")
    public void ShowImage(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") Long id)
            throws IOException {

        ImageStore imageStore = imageStoreService.findById(id);
        File file = new File(imageStore.getPath());
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
        } catch (Exception e) {
            return;
        }
        // 得到文件大小
        byte data[] = new byte[fis.available()];
        fis.read(data);
        // 读数据
        response.setContentType("image/*");
        // 设置返回的文件类型
        OutputStream outStream = response.getOutputStream();
        // 得到向客户端输出二进制数据的对象
        outStream.write(data);
        // 输出数据
        outStream.flush();
        outStream.close();
        fis.close();
    }


}